import dataType from './dataType';

/** 返回获取表头 */
export const renderHeader = (columns, index) => {
  if (!columns || columns.length <= index) {
    return '-';
  }
  const column = columns[index];
  const html = [];
  html.push('<div class="kry-excel-header">');
  if (column.required) {
    html.push(`<p class="kry-excel-header-title">${column.name}<span class="kry-excel-header-required">*</span></p>`);
  } else {
    html.push(`<p class="kry-excel-header-title">${column.name}</p>`);
  }
  if (column.descrbe) {
    html.push(`<p class="kry-excel-header-descrbe">${column.descrbe}</p>`);
  }
  html.push('</div>');
  return html.join('');
};

/** 判断是空行 */
export const isEmptyRow = (rowData) => {
  for (let i = 0, ilen = rowData.length; i < ilen; i += 1) {
    if (rowData[i] !== null && rowData[i] !== undefined && rowData[i] !== '') {
      return false;
    }
  }
  return true;
};


/** 构建表格数据 */
export const renderDatas = (datas, defaultRow = 1) => {
  const result = [];
  if (datas) {
    datas.map(item => result.push(item));
  }
  while (result.length < defaultRow) {
    result.push([]);
  }
  if (!isEmptyRow(result[result.length - 1])) {
    result.push([]);
  }
  return result;
};

const getBasicValidator = column => (value, callback) => {
  const { min, max, required, type } = column;
  let flag = true;
  if (required && !value) {
    flag = false;
  }
  if (type === dataType.text || type === dataType.autocomplete) {
    if (min !== undefined && min != null && (!value || value.length < min)) {
      flag = false;
    }
    if (max !== undefined && max != null && (!value || value.length > max)) {
      flag = false;
    }
  } else if (type === dataType.numeric) {
    if (min !== undefined && min != null && (!value || value < min)) {
      flag = false;
    }
    if (max !== undefined && max != null && (!value || value > max)) {
      flag = false;
    }
  }
  callback(flag);
};


/** 构建表格的列控制信息 */
export const renderColumns = (columns) => {
  const columnProps = [];
  if (columns) {
    columns.map(column => columnProps.push({
      ...column,
      validator: column.validator || getBasicValidator(column),
    }));
  }
  return columnProps;
};
